/**
 * Copyright (c) 时间, Tal.Ben 袁东昊 (ydonghao2@gmail.com).
 *
 * 版权
 */
package com.talben.soudian.ui;

import org.apache.http.Header;
import org.json.JSONObject;

import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import butterknife.InjectView;

import com.loopj.android.http.AsyncHttpResponseHandler;
import com.talben.soudian.AppContext;
import com.talben.soudian.R;
import com.talben.soudian.TDevice;
import com.talben.soudian.api.SouDianAPI;
import com.talben.soudian.base.BaseActivity;
import com.talben.soudian.bean.User;
import com.talben.soudian.util.SimpleTextWatcher;
import com.talben.soudian.util.StringUtils;

/**
 * @Title: ForgetPasswordActivity.java
 * @Package com.talben.soudian.ui
 * @Description: 忘记密码
 * @author Tal.Ben
 * @date 2015年5月24日 下午3:32:26
 * @version v1.0
 */
public class ForgetPasswordActivity extends BaseActivity{

    @InjectView(R.id.et_phone)
    EditText mEtPhone;

    @InjectView(R.id.et_email)
    EditText mEtEmail;
    
    @InjectView(R.id.iv_forget_password_phone)
    View mIvClearPhone;
    
    @InjectView(R.id.iv_forget_password_email)
    View mIvClearEmail;
    
    @InjectView(R.id.btn_find_password)
    Button mBtnFindPassword;
    
    private String mPhone;
    private String mEmail;
    
    private final TextWatcher mPhoneWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        	mIvClearPhone
                    .setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
                            : View.VISIBLE);
        }
    };
    private final TextWatcher mEmailWatcher = new SimpleTextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before,
                int count) {
        	mIvClearEmail
                    .setVisibility(TextUtils.isEmpty(s) ? View.INVISIBLE
                            : View.VISIBLE);
        }
    };
    
    @Override
    protected int getLayoutId() {
        return R.layout.activity_forget_password;
    }
    
    @Override
    protected int getActionBarTitle() {
        return R.string.forget_password;
    }
	
    @Override
    protected boolean hasBackButton() {
        return true;
    }
    
	@Override
	public void onClick(View v) {
		int id = v.getId();
        switch (id) {
        case R.id.iv_forget_password_phone:
        	mEtPhone.getText().clear();
        	mEtPhone.requestFocus();
            break;
        case R.id.iv_forget_password_email:
        	mEtEmail.getText().clear();
        	mEtEmail.requestFocus();
            break;
        case R.id.btn_find_password:
            handleForgetPassword();
            break;
        default:
            break;
        }
	}

	private void handleForgetPassword() {
		if (!prepareForForgetPassword()) {
            return;
        }
		
		mPhone = mEtPhone.getText().toString();
	    mEmail = mEtEmail.getText().toString();
		
	    showWaitDialog(R.string.progress_forget_password);
	    SouDianAPI.forgetPassword(mPhone, mEmail, mHandler);
	}

	private boolean prepareForForgetPassword() {
		 if (!TDevice.isNetworkReady(getApplicationContext())) {
	        AppContext.showToastShort(R.string.tip_no_internet);
	        return false;
	    }
		String uPhone = mEtPhone.getText().toString();
		if (StringUtils.isEmpty(uPhone)) {
			AppContext.showToastShort(R.string.tip_please_input_phone);
			mEtPhone.requestFocus();
            return false;
		} else if (!uPhone.matches("[1][358]\\d{9}")) {
			AppContext.showToastShort(R.string.tip_illegal_phone);
			mEtPhone.setText("");
			mEtPhone.requestFocus();
            return false;
		}
		String uEmail = mEtEmail.getText().toString();
		if (StringUtils.isEmpty(uEmail)) {
			AppContext.showToastShort(R.string.tip_please_input_email);
			mEtPhone.requestFocus();
            return false;
		} else if (!StringUtils.isEmail(uEmail)) {
			AppContext.showToastShort(R.string.tip_illegal_email);
			mEtPhone.setText("");
			mEtPhone.requestFocus();
            return false;
		}
		return true;
	}

	private final AsyncHttpResponseHandler mHandler = new AsyncHttpResponseHandler() {

		@Override
		public void onFailure(int arg0, Header[] arg1, byte[] arg2,
				Throwable arg3) {
			hideWaitDialog();
			String result;
			try {
				result = new String(arg2,"utf-8");
				JSONObject resJObj = new JSONObject(result);
				AppContext.showToast(resJObj.getString("msg"));
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
            
		}

		@Override
		public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
			// 处理成功后的动作
			try {
				//处理Json
                String result = new String(arg2,"utf-8");
                JSONObject resJObj = new JSONObject(result);
                if (resJObj.getString("result").equals("success")) {
                    hideWaitDialog();
                    handleFindPasswordSuccess();
				} else if (resJObj.getString("result").equals("false")) {
					AppContext.getInstance().cleanLoginInfo();
                    hideWaitDialog();
                    AppContext.showToast(resJObj.getString("msg"));
				}
			} catch (Exception e) {
				e.printStackTrace();
                onFailure(arg0, arg1, arg2, e);
			}
		}
    };
	
    private void handleFindPasswordSuccess() {
    	AppContext.showToast("找回密码成功，请到邮箱验证。");
	}
    
	@Override
	public void initView() {
		mBtnFindPassword.setOnClickListener(this);
		mIvClearPhone.setOnClickListener(this);
		mIvClearEmail.setOnClickListener(this);
		
		mEtPhone.addTextChangedListener(mPhoneWatcher);
		mEtEmail.addTextChangedListener(mEmailWatcher);
	}
	

	@Override
	public void initData() {
		// TODO Auto-generated method stub
		
	}

}

